package com.xcx.demo.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xcx.demo.dao.UserDAO;
import com.xcx.demo.entity.OpenIdJson;
import com.xcx.demo.entity.User;
import com.xcx.demo.result.Result;
import com.xcx.demo.result.ResultFactory;
import com.xcx.demo.service.UserService;
import com.xcx.demo.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
public class LoginController {

    @Autowired
    UserService userService;
    @Autowired
    UserDAO userDAO;

    private String appID = "wx013c73f5e763c130";  //先这样吧，懒得多写一个类了
    private String appSecret = "de4d95937583294a5ccddade42df8ae0";

    @PostMapping("/login")
    @CrossOrigin
    public String userLogin(@RequestParam("code") String code) throws IOException{
        String result="";
        try {//请求微信服务器，用code换取openid。HttpUtil是工具类，后面会给出实现，Configure类是小程序配置信息，后面会给出代码
            result = HttpUtil.doGet(
                    "https://api.weixin.qq.com/sns/jscode2session?appid="
                            + this.appID + "&secret="
                            + this.appSecret + "&js_code="
                            + code
                            + "&grant_type=authorization_code", null);
        }catch (Exception e){
            e.printStackTrace();
        }
        ObjectMapper mapper = new ObjectMapper();
        OpenIdJson openIdJson = mapper.readValue(result,OpenIdJson.class);

        if (!userService.isExist(openIdJson.getOpenid())) { //校验数据库中用户是否存在
            userService.save(openIdJson.getOpenid(),openIdJson.getSession_key());
        }

//        userService.save(openIdJson.getOpenid(),openIdJson.getSession_key());
//        System.out.println(openIdJson.getOpenid());

        return result;
    }
}
